//
//  HandleViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/7.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SwiftyJSON

class HandleViewController: KMViewController {
    
    fileprivate var headView : HandleHeadView!
    fileprivate let typeView = TypeView()
    
    fileprivate var bankType = allBanks //银行
    fileprivate var useType = allUse //用途
    fileprivate var gradeType = allGrade //等级
    fileprivate var curLoction = "中山市" //位置
    fileprivate var page = 1 //页码
    
    fileprivate var tag = 0 //当前选中模块
    
    fileprivate var dataArray = [HandleModel]() //办卡详情信息
    
    fileprivate var typeArray = [[String]]() //类型信息
    
    fileprivate let cellId = "handleCell"
    
    fileprivate var titleLabel : UILabel! //标题
    
    fileprivate let cityLabel = UILabel() //右上角城市标签

    fileprivate var footerView : BankCenterView!
    
    fileprivate var titleCount : String! { //信息数量
        didSet{
            titleLabel.text = "为你找到" + titleCount + "张符合条件的卡"
        }
    }
    
    fileprivate var tableView : UITableView!
    
    init(bankType:String? = nil,useType:String? = nil) {
        super.init(nibName: nil, bundle: nil)
        
        self.bankType = bankType ?? allBanks
        self.useType = useType ?? allUse
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = handleCard
        addSubView()
        createRightButton()
        getTypeNews()
        getCardNews()
    }
    
    //MARK: 添加子视图
    fileprivate func addSubView() {
        
        headView = HandleHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 40)))
        headView.bankView.text = bankType
        headView.useView.text = useType
        headView.bankView.addTarget(self, action: #selector(selectTypeAction(sender:)), for: .touchUpInside)
        headView.useView.addTarget(self, action: #selector(selectTypeAction(sender:)), for: .touchUpInside)
        headView.gradeView.addTarget(self, action: #selector(selectTypeAction(sender:)), for: .touchUpInside)
        self.view.addSubview(headView)
        
        titleLabel = UILabel.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(30)))
        titleLabel.textAlignment = .center
        titleLabel.backgroundColor = UIColor.mineColor()
        titleLabel.textColor = UIColor.lightGray
        titleLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        
        footerView = BankCenterView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 260)))
        footerView.centerDelegate = self
        footerView.moreButton.addTarget(self, action: #selector(loadMore(sender:)), for: .touchUpInside)
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = titleLabel
        tableView.tableFooterView = footerView
        tableView.register(HandleCell.self, forCellReuseIdentifier: cellId)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
        }
        
        typeView.isHidden = true
        typeView.typeDelegate = self
        self.view.addSubview(typeView)
        
        typeView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
    }
    
    //MARK: 导航栏右键
    fileprivate func createRightButton() {
        
        let button = UIButton()
        button.addTarget(self, action: #selector(selectCity(sender:)), for: .touchUpInside)
        self.navigationController?.navigationBar.addSubview(button)
        
        
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "location")
        button.addSubview(imageView)
        
        
        cityLabel.text = self.curLoction
        cityLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        cityLabel.textColor = UIColor.white
        button.addSubview(cityLabel)
        
        button.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(RATIO(maxNum: -8))
            make.centerY.height.equalToSuperview()
            make.width.equalTo(RATIO(maxNum: 120))
        }
        
        cityLabel.snp.makeConstraints { (make) in
            make.right.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        imageView.snp.makeConstraints { (make) in
            make.right.equalTo(cityLabel.snp.left)
            make.centerY.equalTo(cityLabel)
            make.width.height.equalTo(RATIO_H(maxNum: 20))
        }
        
        
    
    }
    
    
    //MARK: 选择城市
    @objc fileprivate func selectCity(sender:UIButton) {
        
        let cityVC = CityViewController.init(currentCity:self.curLoction)
        cityVC.cityBlock = { (cityName) in
            self.cityLabel.text = cityName
            self.page = 1
            self.getCardNews(curLoction: cityName)
        }
        self.navigationController?.pushViewController(cityVC, animated: true)
    }
    
    //MARK: 选择类型
    @objc fileprivate func selectTypeAction(sender:ButtonView) {
        
        if self.typeArray.count == 0 {
            return
        }
        
        if sender.image == #imageLiteral(resourceName: "up_arrow") {
            sender.image = #imageLiteral(resourceName: "bottom_arrow")
            self.typeView.isHidden = true
        }else{
            sender.image = #imageLiteral(resourceName: "up_arrow")
            self.typeView.isHidden = false
        }
        
        self.tag = sender.tag
        
        switch sender.tag {
        case 0://银行
            self.headView.useView.image = #imageLiteral(resourceName: "bottom_arrow")
            self.headView.gradeView.image = #imageLiteral(resourceName: "bottom_arrow")
            self.typeView.text = allBanks
        case 1://用途
            self.headView.bankView.image = #imageLiteral(resourceName: "bottom_arrow")
            self.headView.gradeView.image = #imageLiteral(resourceName: "bottom_arrow")
            self.typeView.text = allUse
        case 2://等级
            self.headView.bankView.image = #imageLiteral(resourceName: "bottom_arrow")
            self.headView.useView.image = #imageLiteral(resourceName: "bottom_arrow")
            self.typeView.text = allGrade
        default:
            break
        }
        
        self.typeView.dataArray = self.typeArray[sender.tag]
        self.typeView.collectionView.reloadData()
        
        var count = self.typeView.dataArray.count/3
        if self.typeView.dataArray.count%3 != 0 {
            count += 1
        }
        
        self.typeView.headView.snp.remakeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(40) * CGFloat(count + 1))
            
        }
        
    }
    
    //MARK: 查看更多
    @objc fileprivate func loadMore(sender:UIButton) {
        
        sender.setTitle(loadHard + "...", for: .normal)
        getCardNews()
    }
    
    //MARK: 获取办卡信息
    fileprivate func getCardNews(bankType:String?=nil,useType:String?=nil,gradeType:String?=nil,curLoction:String?=nil) {
        
        if self.page == 1{
            self.dataArray.removeAll()
        }
    
        var parameters = ["city":curLoction ?? self.curLoction,"p":"\(self.page)"]
        if let type = bankType {
            if type != allBanks{
                parameters["bank"] = type
            }else{
                parameters.removeValue(forKey: "bank")
            }
            
        }else{
            if self.headView.bankView.text != allBanks {
                parameters["bank"] = self.headView.bankView.text
            }else{
                parameters.removeValue(forKey: "bank")
            }
        }
        
        if let type = useType {
            if type != allUse {
                parameters["type"] = type
            }else{
                parameters.removeValue(forKey: "type")
            }
        }else{
            if self.headView.useView.text != allUse {
                parameters["type"] = self.headView.useView.text
            }else{
                parameters.removeValue(forKey: "type")
            }
        }
        
        if let type = gradeType {
            if type != allGrade {
                parameters["lavel"] = type
            }else{
                parameters.removeValue(forKey: "lavel")
            }
        }else{
            if self.headView.gradeView.text != allGrade {
                parameters["lavel"] = self.headView.gradeView.text
            }else{
                parameters.removeValue(forKey: "lavel")
            }
        }
        
        
        KMTool.requestGetData(URLString: url_applicationCard, parameters: parameters) { (data) in

            do{
                let json = try JSON.init(data: data)
                if let array = json.arrayObject as? [[String:Any]] {
                    for dic in array {
                        let model = HandleModel.setModel(with: dic)
                        self.dataArray.append(model)
                    }
                    
                    self.page += 1
                    self.titleCount = self.dataArray.first?.count_num
                    self.tableView.reloadData()
                    self.footerView.moreButton.setTitle(viewMore, for: .normal)
                    
                    if array.count == 0 {
                        self.footerView.moreButton.setTitle(loadAll, for: .normal)
                    }
                    
                }
            }catch{
                self.dataArray.removeAll()
                self.tableView.reloadData()
                self.footerView.moreButton.setTitle(loadAll, for: .normal)
                self.titleCount = "0"
            }
            
            
            
        }
        
    }
    
    //MARK: 获取类型信息
    fileprivate func getTypeNews(curLoction:String?=nil) {
        
        KMTool.requestGetData(URLString: url_cardCondition, parameters: ["city":self.curLoction]) { (data) in

            let json = try? JSON.init(data: data)
            
            //银行
            if let bank = json!["bank"].arrayObject {
                self.typeArray.append(bank as! [String])
            }
            //用途
            if let yonghu = json!["yonghu"].arrayObject {
                self.typeArray.append(yonghu as! [String])
            }
            //等级
            if let  lavel = json!["lavel"].arrayObject {
                self.typeArray.append(lavel as! [String])
            }
            
        }
        
       
    }
    
    //MARK: 点击屏幕
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        self.hideTypeView()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension HandleViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 100)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? HandleCell
        cell?.model = dataArray[indexPath.row]
        cell?.requestBtn.tag = indexPath.row
        cell?.requestBtn.addTarget(self, action: #selector(freeApplication(sender:)), for: .touchUpInside)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let urlString = "https://m.kameng98.com/mobile/details/i" + dataArray[indexPath.row].id!
        let webVC = WebViewController.init(urlString: urlString, title: dataArray[indexPath.row].credit_name)
        webVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(webVC, animated: true)
    }
    
    //MARK: 免费申请
    @objc fileprivate func freeApplication(sender:UIButton) {
        
        var urlString = ""
        
        let model = dataArray[sender.tag]
        if model.app_apply_access != "" {
            urlString = model.app_apply_access!
        }else if model.m_apply_access != "" {
            urlString = model.m_apply_access!
        }else if model.apply_access != "" {
            urlString  = model.apply_access!
        }
        
        
        if urlString == "" {
            return
        }
        
        KMTool.generateRecords(idString: model.id!)
        let webVC = WebViewController.init(urlString: urlString, title: dataArray[sender.tag].credit_name)
        webVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(webVC, animated: true)
    }
}

extension HandleViewController : TypeViewDelegate {
    
    //MARK: 选择办卡类型
    func selectType(title: String) {
        switch self.tag {
        case 0:
            if self.headView.bankView.text == title {
                self.hideTypeView()
                return
            }
            self.page = 1
            self.getCardNews(bankType:title)
            self.headView.bankView.text = title
        case 1:
            if self.headView.useView.text == title {
                self.hideTypeView()
                return
            }
            self.page = 1
            self.getCardNews(useType:title)
            self.headView.useView.text = title
        case 2:
            if self.headView.gradeView.text == title {
                self.hideTypeView()
                return
            }
            self.page = 1
            self.getCardNews(gradeType:title)
            self.headView.gradeView.text = title
        default:
            break
        }
        
        
        self.hideTypeView()
    }
    
    //MARK: 隐藏选择类型视图
    fileprivate func hideTypeView() {
        
        self.typeView.isHidden = true
        self.headView.useView.image = #imageLiteral(resourceName: "bottom_arrow")
        self.headView.bankView.image = #imageLiteral(resourceName: "bottom_arrow")
        self.headView.gradeView.image = #imageLiteral(resourceName: "bottom_arrow")
    }
    
}


extension HandleViewController : BankCenterViewDelegate {
    
    //MARK: 选择银行类型
    func selectBankType() {
      
        self.footerView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 260))
        self.tableView.tableFooterView = self.footerView
    }
    
    //MARK: 选择银行卡
    func selectCardType(title: String, imageurl: String) {
        
        if self.headView.bankView.text == title && self.footerView.bankType == 1 {
            return
        }
        
        
        if self.footerView.bankType == 1 {
            self.headView.bankView.text = title
            self.page = 1
            self.getCardNews(bankType: title)
        }else{
            let centerVC = CardCenterViewController.init(title:title,imageUrl:imageurl)
            self.navigationController?.pushViewController(centerVC, animated: true)
        }
    }
    
    
    //MARK: 更多银行信息
    func moreBankCard(title: String) {
        
        if title == bankCardCenter || title == bankCardApplication {
            self.footerView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 580))
            
        }else{
            self.footerView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 260))
        }
        
        self.tableView.tableFooterView = self.footerView
    }
}






